/*
 * Copyright 2002-2006 the original author or authors. Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language governing permissions and limitations under the
 * License.
 */
package pikes.html.propertyeditors;

import java.beans.PropertyEditor;
import java.beans.PropertyEditorSupport;
import java.util.HashMap;
import java.util.Map;

import pikes.html.HtmlDocType;
import pikes.html.xhtml.version10.FrameSetDocType;
import pikes.html.xhtml.version10.StrictDocType;
import pikes.html.xhtml.version10.TransitionalDocType;
import pikes.html.xhtml.version11.XHtml11DocType;

/**
 * Property editor for {@link HtmlDocType}. The accepted string values are 'strict', transitional', 'frameset' and
 * 'xhtml11'.
 * @author Peter Bona
 */
public class HtmlDocTypeEditor extends PropertyEditorSupport implements PropertyEditor {

	private static Map<String, HtmlDocType> DOC_TYPES = new HashMap<String, HtmlDocType>();

	static {
		DOC_TYPES.put("strict", new StrictDocType());
		DOC_TYPES.put("transitional", new TransitionalDocType());
		DOC_TYPES.put("frameset", new FrameSetDocType());
		DOC_TYPES.put("xhtml11", new XHtml11DocType());
	}

	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		if (!DOC_TYPES.containsKey(text)) {
			throw new IllegalArgumentException(text + " is not allowed HTML doc type");
		}

		setValue(DOC_TYPES.get(text));
	}

	@Override
	public String getAsText() {
		Object value = getValue();
		if (value == null) {
			return "";
		}

		if (!(value instanceof HtmlDocType)) {
			return "";
		}

		HtmlDocType docType = (HtmlDocType) value;

		if (!DOC_TYPES.containsValue(docType)) {
			return "";
		}

		for (Map.Entry<String, HtmlDocType> entry : DOC_TYPES.entrySet()) {
			if (entry.getValue().equals(docType)) {
				return entry.getKey();
			}
		}

		return "";
	}

}
